package com.micro.plugins.oss.realize;

import com.micro.common.MicroResponseCode;
import com.micro.core.exception.BizException;
import com.micro.plugins.oss.enums.OssRuleFlag;
import com.micro.plugins.oss.executor.AbstractOssExecutor;
import com.micro.plugins.oss.executor.OssRuleExecutor;
import com.micro.plugins.oss.load.OssLoadConfiguration;
import com.micro.plugins.oss.storage.QiNiuStorage;
import com.micro.plugins.oss.vo.UploadFile;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * <h1>七牛云</h1>
 * @author LevelCoder
 * @version V1.0.0
 * @email LevelCoder@126.com
 * @date 2020/5/8
 */
@Slf4j
@Component
public class QiniuCloudStorage extends AbstractOssExecutor implements OssRuleExecutor {

    /**
     * <h2>引入配置文件</h2>
     */
    private final OssLoadConfiguration ossLoadConfiguration;

    /**
     * 七牛文件上传管理器
     */
    private UploadManager uploadManager;

    /**
     * 七牛云
     */
    private Auth auth;

    /**
     * 七牛云配置
     */
    private QiNiuStorage qiNiuStorage;


    @Autowired
    public QiniuCloudStorage(OssLoadConfiguration ossLoadConfiguration) {
        this.ossLoadConfiguration = ossLoadConfiguration;
        this.qiNiuStorage = ossLoadConfiguration.getQiNiuStorage();
        init();

    }


    private void init() {
        uploadManager = new UploadManager(new Configuration(Zone.autoZone()));
        auth = Auth.create(qiNiuStorage.getAccessKey(), qiNiuStorage.getSecretKey());
    }


    @Override
    public OssRuleFlag ruleConfig() {
        return OssRuleFlag.OSS_SERVICE_PROVIDER_QINIUYUN;
    }

    @Override
    public String upload(UploadFile uploadFile) {
        try {
            String token = null;
            String domain = null;
            for (QiNiuStorage.QiniuBucket qiniuBucket : qiNiuStorage.getQiniuBucketList()) {
                if (qiniuBucket.getBucketName().equals(uploadFile.getUploadType())){
                    token = auth.uploadToken(qiniuBucket.getBucketName());
                    domain = qiniuBucket.getBucketDomain();
                }
            }
            String filePath = getPath(qiNiuStorage.getPrefix(),uploadFile.getSuffix());
            Response res = uploadManager.put(uploadFile.getUploadData(), filePath, token);
            if (!res.isOK()) {
                throw new RuntimeException("上传七牛出错：" + res.toString());
            }
            return domain + "/" + filePath;
        } catch (Exception e) {
            throw new BizException(MicroResponseCode.UPLOAD_QINIU_FAILED.getResponseCode(), MicroResponseCode.UPLOAD_QINIU_FAILED.getResponseMessage());
        }
    }
}
